package models

import (
	"errors"
	"time"

	"github.com/jinzhu/gorm"
)

// Template 结构体定义
type Template struct {
	Id            int    `gorm:"column:id"`
	UserId        int    `gorm:"column:uid"`
	MdId          int    `gorm:"column:md_id"`
	Title         string `gorm:"column:title"`
	Description   string `gorm:"column:description"`
	Keywords      string `gorm:"column:keywords"`
	CategoriesID  int    `gorm:"column:categories_id"`
	SceneId       int    `gorm:"column:scene_id"`
	CollectionNum int    `gorm:"column:collection_num"`
	LikeNum       int    `gorm:"column:like_num"`
	PayType       int    `gorm:"column:pay_type"`
	Price         string `gorm:"column:price"`
	MindId        string `gorm:"column:mind_id"`
	ImageUrl      string `gorm:"column:image_url"`
	Createtime    int64  `gorm:"column:create_time"`
	Updatetime    int64  `gorm:"column:update_time"`
}
type template struct {
	Id           int    `json:"id"`
	UserId       int    `json:"uid" gorm:"column:uid"`
	MdId         int    `json:"md_id"`
	Title        string `json:"title"`
	Description  string `json:"description"`
	Keywords     string `json:"keywords"`
	CategoriesID int    `json:"categories_id"`
	SceneId      int    `json:"scene_id"`
	PayType      int    `json:"pay_type" gorm:"column:pay_type" `
	Price        string `json:"price"`
	MindId       string `json:"mind_id"`
	ImageUrl     string `json:"image_url"`
	Createtime   int64  `json:"create_time" gorm:"column:create_time"`
	// Updatetime   int64  `json:"update_time" gorm:"column:update_time"`
}

// func (tag *Template) BeforeCreate(scope *gorm.Scope) error {
// 	scope.SetColumn("create_time", time.Now().Unix())
// 	return nil
// }

func AddTemplate(data map[string]interface{}) (bool, error) {
	// 从 data 中提取各字段的值，并进行类型断言
	mdId, ok := data["md_id"].(int)
	if !ok {
		return false, errors.New("md_id 类型断言失败，期望 int 类型")
	}
	title, ok := data["title"].(string)
	if !ok {
		return false, errors.New("title 类型断言失败，期望 string 类型")
	}
	description, ok := data["description"].(string)
	if !ok {
		return false, errors.New("description 类型断言失败，期望 string 类型")
	}
	keywords, ok := data["keywords"].(string)
	if !ok {
		return false, errors.New("keywords 类型断言失败，期望 string 类型")
	}
	categoriesID, ok := data["categories_id"].(int)
	if !ok {
		return false, errors.New("categories_id 类型断言失败，期望 int 类型")
	}
	sceneId, ok := data["scene_id"].(int)
	if !ok {
		return false, errors.New("scene_id 类型断言失败，期望 int 类型")
	}
	payType, ok := data["pay_type"].(int)
	if !ok {
		return false, errors.New("pay_type 类型断言失败，期望 int 类型")
	}
	price, ok := data["price"].(string)
	if !ok {
		return false, errors.New("price 类型断言失败，期望 string 类型")
	}
	mindId, ok := data["mind_id"].(string)
	if !ok {
		return false, errors.New("mind_id 类型断言失败，期望 string 类型")
	}
	imageUrl, ok := data["image_url"].(string)
	if !ok {
		return false, errors.New("image_url 类型断言失败，期望 string 类型")
	}
	userId, ok := data["uid"].(int)
	if !ok {
		return false, errors.New("userid 类型断言失败，期望 string 类型")
	}

	timestamp := time.Now().Unix()

	// 创建 Template 结构体实例
	template := Template{
		UserId:       userId,
		MdId:         mdId,
		Title:        title,
		Description:  description,
		Keywords:     keywords,
		CategoriesID: categoriesID,
		SceneId:      sceneId,
		PayType:      payType,
		Price:        price,
		MindId:       mindId,
		ImageUrl:     imageUrl,
		Createtime:   timestamp,
		Updatetime:   timestamp,
	}

	// 执行数据库插入操作
	result := db.Create(&template)
	if result.Error != nil {
		return false, result.Error
	}

	return true, nil
}

// GetTemplateList 查询模板列表
func GetTemplateList(limit int, offset int, title string, categoryID int, sceneId int, payType int, order int) (result []template) {
	query := db
	if title != "" {
		query = query.Where("title LIKE ?", "%"+title+"%")
	}
	if categoryID != 0 {
		query = query.Where("categories_id = ?", categoryID)
	}
	if sceneId != 0 {
		query = query.Where("scene_id = ?", sceneId)
	}
	if payType != 0 && payType != 3 {
		query = query.Where("pay_type = ?", payType)
	}
	query = query.Where("status =?", 1)
	if order == 0 {
		query = query.Order("create_time DESC")
	} else if order == 1 {
		query = query.Order("view_num DESC")
	} else if order == 2 {
		query = query.Order("id DESC")
	} else if order == 3 {
		query = query.Order("collection_num DESC")
	}
	query.Limit(limit).Offset(offset).Find(&result)
	return
}

// GetTemplateTotal 查询模板总数
func GetTemplateTotal(title string, categoryID int, sceneId int, payType int) int {
	var count int64
	query := db

	if title != "" {
		query = query.Where("title LIKE ?", "%"+title+"%")
	}

	if categoryID != 0 {
		query = query.Where("categories_id = ?", categoryID)
	}
	if sceneId != 0 {
		query = query.Where("scene_id = ?", categoryID)
	}
	if payType != 0 && payType != 3 {
		query = query.Where("pay_type = ?", payType)
	}
	query.Model(&template{}).Count(&count)
	return int(count)
}

// TemplateDecremental 递增方法
func TemplateIncremental(action int, templateId int) (count int) {
	var updatedProduct Template
	var num = 0
	switch action {
	case 1:
		db.Model(&updatedProduct).Where("id = ?", templateId).UpdateColumn("collection_num", gorm.Expr("collection_num + ?", 1))
		db.First(&updatedProduct, templateId)
		num = updatedProduct.CollectionNum
	case 2:
		db.Model(&updatedProduct).Where("id = ?", templateId).UpdateColumn("like_num", gorm.Expr("like_num + ?", 1))
		db.First(&updatedProduct, templateId)
		num = updatedProduct.LikeNum
	}
	return num
}

// TemplateDecremental 递减方法
func TemplateDecremental(action int, templateId int) (count int) {
	var updatedProduct Template
	var num = 0
	switch action {
	case 1:
		db.Model(&updatedProduct).Where("id = ?", templateId).UpdateColumn("collection_num", gorm.Expr("collection_num - ?", 1))
		db.First(&updatedProduct, templateId)
		num = updatedProduct.CollectionNum
	case 2:
		db.Model(&updatedProduct).Where("id = ?", templateId).UpdateColumn("like_num", gorm.Expr("like_num - ?", 1))
		db.First(&updatedProduct, templateId)
		num = updatedProduct.LikeNum
	}
	return num
}
func GetTemplateUid(templateId int) (uid int) {
	var result Template
	db.Select("uid").First(&result, templateId)
	return result.UserId
}
